from __future__ import with_statement
from contextlib import contextmanager
try:
    # import pywin32 module bits, can be found on:
    # http://sourceforge.net/projects/pywin32/
    import win32clipboard as wcb  
    import win32con  
 
    @contextmanager  
    def WinClipboard():  
        """ 
        A context manager for using the windows clipboard safely. 
        """  
        try:  
            wcb.OpenClipboard()  
            yield  
        finally:  
            wcb.CloseClipboard()  
  
    def getcbtext():  
        with WinClipboard():  
            return wcb.GetClipboardData(win32con.CF_TEXT)  
  
    def setcbtext(text):  
        with WinClipboard():  
            wcb.EmptyClipboard()  
            wcb.SetClipboardText(text)  
  
except ImportError, e:  
    # try gtk.  If that doesn't work, just let the exception go  
    import gtk  
  
    def getcbtext():  
        return gtk.Clipboard().wait_for_text()  
  
    def setcbtext(text):  
        cb = gtk.Clipboard()  
        cb.set_text(text)  
        cb.store()
